package camid.distribution.activeobject;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import camid.distribution.broker.Requestor;
import camid.distribution.protocol.Endpoint;
import camid.distribution.protocol.InvocationDescriptor;

public class RemoteInvocationHandler implements InvocationHandler {

	private String sessionId;
	
	private String objectId;
	
	private Class<?> entityClass;
	
	private Requestor requestor;
	
	private Endpoint endpoint;
	
	private static final Logger logger = LogManager.getLogger(RemoteInvocationHandler.class.getName());
	
	public RemoteInvocationHandler(String sessionId, String objectId, Class<?> entityClass, Requestor requestor, Endpoint endpoint) {
		this.sessionId = sessionId;
		this.objectId = objectId;
		this.entityClass = entityClass;
		this.endpoint = endpoint;
		this.requestor = requestor;
		
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] params)
			throws Throwable 
	{
		InvocationDescriptor invocationDescriptor = new InvocationDescriptor(
				sessionId, objectId, entityClass.getCanonicalName(), 
				method.getName(), params);
		
		if(endpoint != null)
		{
			logger.info("Requesting camid://" + endpoint.getHostname() + ":" + endpoint.getPort() 
				+ "/" + entityClass.getName() + "/" + objectId + "/" + method.getName());
		}
		Object response = requestor.request(endpoint, invocationDescriptor);
		return response;
	}
	
	

}
